package com.nullpointer.xchatfinal.fragment;

import java.util.Calendar;

import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.androidquery.AQuery;
import com.androidquery.callback.ImageOptions;
import com.fourmob.datetimepicker.date.DatePickerDialog;
import com.fourmob.datetimepicker.date.DatePickerDialog.OnDateSetListener;
import com.nullpointer.xchatfinal.R;
import com.nullpointer.xchatfinal.fragment.EditAvatarDialogFragment.OnEditAvatarDialogFragment;
import com.nullpointer.xchatfinal.object.User;
import com.nullpointer.xchatfinal.object.UserInfo;
import com.nullpointer.xchatfinal.object.UserInfo.GenderType;
import com.nullpointer.xchatfinal.service.ChatService;
import com.nullpointer.xchatfinal.utils.DataManager;
import com.nullpointer.xchatfinal.utils.Utils;

public class EditProfileDialogFragment extends DialogFragment implements
		OnDateSetListener {
	private TextView tvTitle;
	private EditText etName;
	private ImageButton ibEditName;
	private EditText etStatus;
	private ImageButton ibEditStatus;
	private Button btAction;
	private boolean isChanged = false;
	private TextView tvMale;
	private TextView tvFemale;
	private TextView tvOther;
	private GenderType gender;
	private ImageView ivAvatar;
	private ImageButton ibEditAvatar;
	private long birthday;
	private int focus = Color.parseColor("#ff8800");
	private int normal = Color.parseColor("#333333");
	private DatePickerDialog datePickerDialog;
	private TextView tvBirthday;
	private ImageButton ibEditBirthday;
	public static final String DATEPICKER_TAG = "datepicker";
	// private String faceBookID;
	private String avatarID;
	private String facebookID;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_profile, container);
		findViewIds(view);
		init();
		setEvent();
		return view;
	}

	private void init() {
		getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
		User currentUser = DataManager.getInstance(getActivity())
				.getCurrentUser();
		UserInfo userInfo = currentUser.getUserInfo();
		tvTitle.setText("Profile id: " + currentUser.getUserID());
		birthday = userInfo.getBirthday();
		if (birthday != 0) {
			tvBirthday.setText(convertTimeLongToDateString(birthday));
		} else {
			tvBirthday.setText("1990/01/01");
		}
		etName.setText(currentUser.getName());
		if (userInfo.getStatus() != null) {
			etStatus.setText(userInfo.getStatus());
		}
		gender = userInfo.getGender();
		if (gender == GenderType.FEMALE) {
			tvFemale.setTextColor(focus);
			tvMale.setTextColor(normal);
			tvOther.setTextColor(normal);
		} else if (gender == GenderType.MALE) {
			tvFemale.setTextColor(normal);
			tvMale.setTextColor(focus);
			tvOther.setTextColor(normal);
		} else if (gender == GenderType.ANY) {
			tvFemale.setTextColor(normal);
			tvMale.setTextColor(normal);
			tvOther.setTextColor(focus);
		}
		etName.setEnabled(false);
		etStatus.setEnabled(false);
		facebookID = userInfo.getFaceBookID();
		avatarID = userInfo.getAvatarID();
		showAvatar(Utils.getSmallAvatarFacebook(avatarID));
	}

	private void showAvatar(String url) {
		if (url == null) {
			ivAvatar.setImageResource(R.drawable.ic_no_avatar);
			return;
		}
		ImageOptions options = new ImageOptions();
		options.round = 5;
		options.fileCache = true;
		options.memCache = true;
		options.targetWidth = 96;
		options.fallback = R.drawable.ic_private_avatar;
		AQuery aq = new AQuery(getActivity());
		aq.id(ivAvatar).image(url, options);
	}

	// private void refreshAvatar(String url) {
	// // AQUtility.cleanCacheAsync(getActivity());
	// // BitmapAjaxCallback.clearCache();
	//
	// showAvatar(url);
	// }

	private String convertTimeLongToDateString(long birthday) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(birthday);
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		return convertDateToString(year, month, day);
	}

	private void setEvent() {
		btAction.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Utils.hideKeyboard(getActivity(), etStatus);
				Utils.hideKeyboard(getActivity(), etName);
				if (isChanged) {
					updateProfile();
				} else {
					dismiss();
				}

			}
		});

		ibEditName.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				etName.setEnabled(true);
				etName.requestFocus();
				setUpdateButton();
			}
		});

		ibEditStatus.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				etStatus.setEnabled(true);
				etStatus.requestFocus();
				setUpdateButton();
			}
		});

		ibEditBirthday.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				int year = 1990;
				int month = 01;
				int day = 01;
				if (birthday != 0) {
					Calendar calendar = Calendar.getInstance();
					calendar.setTimeInMillis(birthday);
					year = calendar.get(Calendar.YEAR);
					month = calendar.get(Calendar.MONTH);
					day = calendar.get(Calendar.DAY_OF_MONTH);
				}
				datePickerDialog = DatePickerDialog.newInstance(
						EditProfileDialogFragment.this, year, month, day, true);
				datePickerDialog.setYearRange(1902, 2000);
				datePickerDialog.setCloseOnSingleTapDay(true);
				FragmentTransaction transaction = getActivity()
						.getSupportFragmentManager().beginTransaction();
				transaction.add(datePickerDialog, DATEPICKER_TAG);
				transaction.commitAllowingStateLoss();
				setUpdateButton();
			}
		});

		etName.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
				if (etName.getText() != null
						&& etName.getText().toString().trim().length() >= 3) {
					if (Utils.checkBadword(etName.getText().toString())) {
						btAction.setText("Don't use sexual content!");
						btAction.setEnabled(false);
					} else {
						btAction.setText("Save");
						btAction.setEnabled(true);
					}
				} else {
					btAction.setText("Name must > 3 char");
					btAction.setEnabled(false);
				}
			}
		});

		etStatus.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

				if (Utils.checkBadword(etStatus.getText().toString())) {
					btAction.setText("Don't use sexual content!");
					btAction.setEnabled(false);
				} else {
					btAction.setText("Save");
					btAction.setEnabled(true);
				}

			}
		});

		tvFemale.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (gender != GenderType.FEMALE) {
					tvFemale.setTextColor(focus);
					tvMale.setTextColor(normal);
					tvOther.setTextColor(normal);
					gender = GenderType.FEMALE;
					setUpdateButton();
				}

			}
		});
		tvMale.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (gender != GenderType.MALE) {
					tvFemale.setTextColor(normal);
					tvMale.setTextColor(focus);
					tvOther.setTextColor(normal);
					gender = GenderType.MALE;
					setUpdateButton();
				}
			}
		});
		tvOther.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (gender != GenderType.ANY) {
					tvFemale.setTextColor(normal);
					tvMale.setTextColor(normal);
					tvOther.setTextColor(focus);
					gender = GenderType.ANY;
					setUpdateButton();
				}
			}
		});

		ibEditAvatar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showEditAvatarFragment();
			}
		});
	}

	protected void updateProfile() {
		String name = etName.getText().toString();
		String status = etStatus.getText().toString();
		if (status.trim().length() == 0) {
			status = "Hi!";
		}
		if (isInfoChanged(name, status, gender, avatarID, birthday)) {
			User currentUser = DataManager.getInstance(getActivity())
					.getCurrentUser();
			currentUser.setName(name);
			UserInfo userInfo = currentUser.getUserInfo();
			userInfo.setAvatarID(avatarID);
			userInfo.setBirthday(birthday);
			userInfo.setGender(gender);
			userInfo.setStatus(status);
			currentUser.setUserInfo(userInfo);
			DataManager.getInstance(getActivity()).setCurrentUser(currentUser);
			boolean isInvisible = DataManager.getInstance(getActivity())
					.getInvisibleSetting();
			ChatService.getInstance().updateProfile(true, isInvisible);
		}
		dismiss();
	}

	private boolean isInfoChanged(String name, String status,
			GenderType gender, String avatarID, long birthday) {
		User currentUser = DataManager.getInstance(getActivity())
				.getCurrentUser();
		UserInfo userInfo = currentUser.getUserInfo();
		if (!name.equals(currentUser.getName())) {
			return true;
		}
		if (!status.equals(userInfo.getStatus())) {
			return true;
		}
		if (gender != userInfo.getGender()) {
			return true;
		}
		if (avatarID == null && userInfo.getAvatarID() != null) {
			return true;
		}
		if (avatarID != null && !avatarID.equals(userInfo.getAvatarID())) {
			return true;
		}
		if (birthday != userInfo.getBirthday()) {
			return true;
		}
		return false;
	}

	protected void setUpdateButton() {
		isChanged = true;
		btAction.setText("Save");
	}

	private void findViewIds(View view) {
		etName = (EditText) view.findViewById(R.id.et_name);
		ibEditName = (ImageButton) view.findViewById(R.id.ib_edit_name);
		etStatus = (EditText) view.findViewById(R.id.et_status);
		ibEditStatus = (ImageButton) view.findViewById(R.id.ib_edit_status);
		btAction = (Button) view.findViewById(R.id.bt_action);
		tvMale = (TextView) view.findViewById(R.id.tv_male);
		tvFemale = (TextView) view.findViewById(R.id.tv_female);
		tvOther = (TextView) view.findViewById(R.id.tv_other);
		tvBirthday = (TextView) view.findViewById(R.id.tv_birthday);
		ibEditBirthday = (ImageButton) view.findViewById(R.id.ib_edit_birthday);
		tvTitle = (TextView) view.findViewById(R.id.tv_title);
		ivAvatar = (ImageView) view.findViewById(R.id.iv_avatar);
		ibEditAvatar = (ImageButton) view.findViewById(R.id.ib_edit_avatar);
	}

	@Override
	public void onDismiss(DialogInterface dialog) {
		super.onDismiss(dialog);
		Utils.hideKeyboard(getActivity(), etStatus);
		Utils.hideKeyboard(getActivity(), etName);
	}

	@Override
	public void onCancel(DialogInterface dialog) {
		super.onCancel(dialog);
		Utils.hideKeyboard(getActivity(), etStatus);
		Utils.hideKeyboard(getActivity(), etName);
	}

//	protected void showChooseImageFragment() {
//		final ChooseImageDialogFragment dialog = new ChooseImageDialogFragment();
//		dialog.setOnChooseImageDialogFragment(new OnChooseImageDialogFragment() {
//
//			@Override
//			public void onGallery() {
//				selectImageFromGallery();
//			}
//
//			@Override
//			public void onCamera() {
//				selectImageFromCamera();
//			}
//		});
//		FragmentTransaction transaction = getActivity()
//				.getSupportFragmentManager().beginTransaction();
//		transaction.add(dialog, "ChooseImageDialogFragmentEditProfile");
//		transaction.commitAllowingStateLoss();
//	}
//
//	protected void selectImageFromGallery() {
//		Intent intent = new Intent(getActivity(), ProcessImage.class);
//		intent.putExtra(ProcessImage.IS_SELECT_IMAGE_FROM_CAMERA, false);
//		intent.putExtra(ProcessImage.ASPECT_RATIO_X, 100);
//		intent.putExtra(ProcessImage.ASPECT_RATIO_Y, 100);
//		startActivityForResult(intent, Common.RequestCode.EDIT_AVATAR_PROFILE);
//	}
//
//	protected void selectImageFromCamera() {
//		Intent intent = new Intent(getActivity(), ProcessImage.class);
//		intent.putExtra(ProcessImage.IS_SELECT_IMAGE_FROM_CAMERA, true);
//		intent.putExtra(ProcessImage.ASPECT_RATIO_X, 100);
//		intent.putExtra(ProcessImage.ASPECT_RATIO_Y, 100);
//		startActivityForResult(intent, Common.RequestCode.EDIT_AVATAR_PROFILE);
//	}

	protected void showEditAvatarFragment() {
		final EditAvatarDialogFragment dialog = EditAvatarDialogFragment
				.newInstance(avatarID);
		dialog.setOnEditAvatarDialogFragment(new OnEditAvatarDialogFragment() {

			@Override
			public void onRefresh() {
				avatarID = Utils.getAvatarIDFromFacebookID(facebookID);
				showAvatar((Utils.getSmallAvatarFacebook(avatarID)));
				setUpdateButton();
			}

			@Override
			public void onDisable() {
				avatarID = null;
				showAvatar(null);
				setUpdateButton();
			}

			@Override
			public void onEnable() {
				avatarID = Utils.getAvatarIDFromFacebookID(facebookID);
				showAvatar((Utils.getSmallAvatarFacebook(avatarID)));
				setUpdateButton();
			}
		});
		FragmentTransaction transaction = getActivity()
				.getSupportFragmentManager().beginTransaction();
		transaction.add(dialog, "EditAvatarDialogFragment");
		transaction.commitAllowingStateLoss();
	}

	@Override
	public void onDateSet(DatePickerDialog datePickerDialog, int year,
			int month, int day) {
		birthday = Utils.convertDateToLongTime(year, month, day);
		tvBirthday.setText(convertDateToString(year, month, day));
	}

	private String convertDateToString(int year, int month, int day) {
		return year + "/" + ((month < 10) ? "0" + month : month) + "/"
				+ ((day < 10) ? "0" + day : day);
	}
}
